<template>
  <div class="qn-form">
    <el-form
      ref="settingForm"
      class="setting-form"
      :rules="formDataRules"
      :model="formData"
      label-position="left"
      label-width="160px"
    >
      <el-form-item label="Accesskey" prop="access_key">
        <el-input v-model.number="formData.access_key" placeholder="七牛云Accesskey" />
      </el-form-item>
      <el-form-item label="Secretkey" prop="secret_key">
        <el-input v-model.number="formData.secret_key" placeholder="七牛云Secretkey" />
      </el-form-item>
      <el-form-item label="Bucket" prop="bucket">
        <el-input v-model.number="formData.bucket" placeholder="七牛云Bucket（请保证bucket为可公共读取的）" />
      </el-form-item>
      <el-form-item label="绑定域名" prop="domain">
        <el-input v-model.number="formData.domain" placeholder="七牛云绑定域名" />
      </el-form-item>
      <el-button type="primary" size="small" @click="submit">确认配置</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'QnForm',
  props: {
    setting: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      formData: {
        access_key: '',
        secret_key: '',
        bucket: '',
        domain: '' // 云存储绑定域名
      },
      formDataRules: {
        access_key: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        secret_key: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        bucket: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        domain: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    setting() {
      if (this.setting.qn) {
        const {
          access_key,
          secret_key,
          bucket,
          domain
        } = this.setting.qn
        this.formData = {
          access_key,
          secret_key,
          bucket,
          domain
        }
      }
    }
  },
  methods: {
    /**
     * 提交
     */
    submit() {
      this.$refs.settingForm.validate((valid) => {
        if (valid) {
          this.$put('setting/media', {
            qn: this.formData
          })
            .then(() => {
              this.$message.success({
                message: '修改成功',
                type: 'success'
              })
            })
            .catch((error) => {
              this.$handleError(error)
            })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .setting-form{
    width: 600px;
  }
</style>
